import React, { useEffect, useState, useRef } from 'react';
import { Button, Modal, Spin, Typography } from 'antd';

import { useRequest, defaultFormatResult } from '@/hooks';

import TwoColHead from '@/pages/SalaryManage/components/TwoColHead';
import { onEditMonthTemplate, querySalaryMonthItemData } from '@/services/salaryManage/salaryCalculate';
import { goToSalarymainadd } from '@/pages/SalaryManage/utils/pageNavigateUtil';

import SalaryItemZone from '../SalaryItemZone';

/**
 * 薪资要素（薪资加项与薪资减项）的选择
 * @param organizationCode 行政机构编码
 * @param currentYear 模板年份
 * @param currentMonth 模板月份
 * @param templateId 模板id
 * @returns {JSX.Element}
 * @constructor
 */
const SalaryTemplateOperate = ({ organizationCode, currentYear, currentMonth, onChange }) => {
    /** 所有薪资加项 */
    const [allAddList, setAllAddList] = useState([]);

    /** 选择的薪资加项 */
    const [usedAddList, setUsedAddList] = useState([]);

    /** 所有薪资减项 */
    const [allLessList, setAllLessList] = useState([]);

    /** 选择的薪资减项 */
    const [usedLessList, setUsedLessList] = useState([]);

    /** 用来存储加减项信息 */
    const listRef = useRef({});

    const { data: salaryMonthItem, run, loading } = useRequest(
        () => querySalaryMonthItemData(organizationCode, currentYear, currentMonth),
        {
            ...defaultFormatResult,
            manual: true
        }
    );

    useEffect(() => {
        if (organizationCode) {
            run();
        }
    }, [organizationCode, currentYear, currentMonth, run]);

    useEffect(() => {
        if (salaryMonthItem) {
            const {
                unusedAddSalaryItems,
                usedAddSalaryItems,
                usedLessSalaryItems,
                unusedLessSalaryItems
            } = salaryMonthItem;

            const listInfo = {
                // 所有薪资加项
                allAddList: [...usedAddSalaryItems, ...unusedAddSalaryItems],
                // 后台存储使用的加项
                usedAddList: [...usedAddSalaryItems],
                // 当前选择的加项
                checkedAddList: [...usedAddSalaryItems],
                // 所有薪资减项
                addLessList: [...usedLessSalaryItems, ...unusedLessSalaryItems],
                // 后台存储使用的减项
                usedLessList: [...usedLessSalaryItems],
                // 当前选择的减项
                checkedLessList: [...usedLessSalaryItems]
            };

            listRef.current = listInfo;
            setAllAddList(listInfo.allAddList);
            setUsedAddList(listInfo.usedAddList);
            setAllLessList(listInfo.addLessList);
            setUsedLessList(listInfo.usedLessList);
        }
    }, [salaryMonthItem]);

    const handleAddChange = newAddCheckedList => {
        if (listRef.current) {
            listRef.current.checkedAddList = newAddCheckedList;
            onChange(listRef.current);
        }
    };

    const handleLessChange = newLestCheckedList => {
        if (listRef.current) {
            listRef.current.checkedLessList = newLestCheckedList;
            onChange(listRef.current);
        }
    };

    return (
        <div>
            <Spin spinning={loading}>
                <SalaryItemZone type="add" list={allAddList} selected={usedAddList} onChange={handleAddChange} />
                <SalaryItemZone type="less" list={allLessList} selected={usedLessList} onChange={handleLessChange} />
            </Spin>
        </div>
    );
};

/**
 * 薪资要素模态框
 * 薪资加、减项的添加与删除
 * @param visible 是否可见
 * @param onCancel 取消的回调
 * @param onOk 保存后的回调
 * @param organizationCode 行政机构
 * @param currentYear 查操作的薪资要素年份
 * @param currentMonth 查操作的薪资要素月份
 * @param templateId 查操作的薪资模板id
 * @returns {JSX.Element}
 * @constructor
 */
const SalaryTemplateModal = ({ visible, onCancel, onOk, organizationCode, currentYear, currentMonth, templateId }) => {
    const [title, setTitle] = useState();
    // 是否做过修改
    const [modified, setModified] = useState(false);
    /** 用来存储加减项信息 */
    const listRef = useRef({});

    const { run: save } = useRequest(onEditMonthTemplate, {
        manual: true,
        defaultFormatResult
    });

    useEffect(() => {
        setTitle(`${+currentMonth}月薪资要素`);
    }, [currentMonth]);

    const handleCheckedChange = listInfo => {
        setModified(true);
        listRef.current = listInfo;
    };

    const handleOnOk = async () => {
        if (modified) {
            const { checkedAddList = [], checkedLessList = [] } = listRef.current;
            const postData = {
                salaryItemIds: [...checkedAddList, ...checkedLessList].map(item => item.id),
                templateId
            };
            const responseData = await save(postData);
            onOk(responseData);
            return;
        }
        // 没有变更时直接关闭弹框
        onCancel();
    };

    const goToAdd = () => {
        if (!modified) {
            onCancel();
            goToSalarymainadd({ query: { entry: 'mul', organizationCode } });
            return;
        }
        Modal.confirm({
            title: '确认',
            content: '有【新增】或【删除】薪资项但还未保存，保存后前往？',
            okText: '是',
            onOk: async () => {
                handleOnOk().then(() => {
                    goToSalarymainadd({ query: { entry: 'mul', organizationCode } });
                });
            },
            cancelText: '否',
            onCancel: () => {
                goToSalarymainadd({ query: { entry: 'mul', organizationCode } });
            }
        });
    };

    return (
        <Modal
            title={title}
            visible={visible}
            onCancel={onCancel}
            onOk={handleOnOk}
            width={1132}
            // style={{ top: 40 }}
            bodyStyle={{ maxHeight: 'calc(100vh - 200px)', overflow: 'auto', padding: '0 36px' }}
            footer={
                <TwoColHead
                    left={
                        <>
                            <Button type="primary" ghost onClick={goToAdd}>
                                新增
                            </Button>
                            <Typography.Text type="secondary">没有所需薪资项？</Typography.Text>
                        </>
                    }
                    right={
                        <>
                            <Button onClick={onCancel}>取消</Button>
                            <Button type="primary" onClick={handleOnOk}>
                                确认
                            </Button>
                        </>
                    }
                    style={{ marginTop: 0, marginBottom: 0 }}
                />
            }
        >
            <SalaryTemplateOperate
                organizationCode={organizationCode}
                currentYear={currentYear}
                currentMonth={currentMonth}
                templateId={templateId}
                onChange={handleCheckedChange}
            />
        </Modal>
    );
};

SalaryTemplateModal.defaultProps = {
    visible: true,
    onOk: () => {}
};

export { SalaryTemplateOperate, SalaryTemplateModal };
